package ru.jexp.rcp.supply.beans.zs;

import java.util.Date;

import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.nebula.widgets.formattedtext.DefaultFormatterFactory;
import org.eclipse.nebula.widgets.formattedtext.FormattedText;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.TraverseEvent;
import org.eclipse.swt.events.TraverseListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;

public class DateCellEditor extends CellEditor {

	private FormattedText dt;

	public DateCellEditor(Composite parent) {
		super(parent);
	}

	@Override
	protected Control createControl(Composite parent) {
		dt = new FormattedText(parent, SWT.NONE);
		dt.setFormatter(DefaultFormatterFactory.createFormatter(Date.class));
		dt.getControl().addTraverseListener(new TraverseListener() {
			public void keyTraversed(TraverseEvent e) {
				if (e.detail == SWT.TRAVERSE_ESCAPE
						|| e.detail == SWT.TRAVERSE_RETURN) {
					e.doit = false;
				}
			}
		});
		/*
		 * dt.addFocusListener(new FocusAdapter() {
		 * 
		 * @Override public void focusLost(FocusEvent e) { if
		 * (!dt.isFocusControl()) { DateCellEditor.this.focusLost(); } } });
		 */
		dt.getControl().addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
				applyEditorValue();
			}
		});
		return dt.getControl();
	}

	protected void applyEditorValue() {
		fireApplyEditorValue();
		deactivate();
	}

	@Override
	protected Object doGetValue() {
		return dt.getValue();
	}

	@Override
	protected void doSetFocus() {
		dt.getControl().setFocus();
	}

	@Override
	protected void doSetValue(Object value) {
		if (value instanceof Date) {
			dt.setValue((Date) value);
		}
	}

}
